using System;
using System.Globalization;
using System.IO;
using BSDS.Core.Infrastructure.Logging;
using BSDS.Core.Model.Services.Geocoding;
using BSDS.Core.Model.Services.Jobs;

namespace BSDS.Core.Data.Local.Jobs
{
    public class GeocodeJobSerializer
    {
        private readonly Logger logger;

        public GeocodeJobSerializer(Logger logger)
        {
            this.logger = logger;
        }

        public void Serialize(GeocodeJob job, string filename)
        {
            logger.Log("Saving job information to file: " + filename);

            using (var writer = new StreamWriter(filename))
            {
                writer.WriteLine(job.Id);
                writer.WriteLine(job.Link);
                writer.WriteLine(job.SubmissionDate.ToString(CultureInfo.InvariantCulture));
                writer.WriteLine(job.Description);
                writer.WriteLine(job.OriginalFilename);
                writer.WriteLine(job.OriginalFormat.Value);
                writer.WriteLine(Enum.GetName(typeof(GeocodingMode), job.Mode));
                writer.WriteLine(job.Command);
            }
        }

        public GeocodeJob Deserialize(string jobFilename)
        {
            using (var reader = new StreamReader(jobFilename))
            {
                return new GeocodeJob
                           {
                               Id = reader.ReadLine(),
                               Link = reader.ReadLine(),
                               SubmissionDate = DateTime.Parse(reader.ReadLine(), CultureInfo.InvariantCulture),
                               Description = reader.ReadLine(),
                               OriginalFilename = reader.ReadLine(),
                               OriginalFormat = DataFormat.Parse(reader.ReadLine()),
                               Mode = (GeocodingMode)Enum.Parse(typeof (GeocodingMode), reader.ReadLine()),
                               Command = reader.ReadLine()
                           };
            }
        }
    }
}